package com.coldworks.coldjoke.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NetworkUtil {
	protected final static Logger log = LoggerFactory
			.getLogger(NetworkUtil.class);
	private static NetworkUtil instance = null;

	private NetworkUtil() {
	}

	public static NetworkUtil getInstance() {
		if (instance == null) {
			synchronized (NetworkUtil.class) {
				if (instance == null) {
					instance = new NetworkUtil();
				}
			}
		}
		return instance;
	}

	public JSONObject getJSONObject(InputStream inputStream) {
		StringBuilder builder = new StringBuilder();
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(inputStream));
		String line = "";
		try {
			while ((line = bufferedReader.readLine()) != null) {
				builder.append(line);
			}
		} catch (IOException e) {
			log.error("", e);
		}
		try {
			JSONObject jsonObject = new JSONObject(builder.toString());
			return jsonObject;
		} catch (Exception e) {
			log.error("", e);
			return null;
		}

	}

	public JSONObject getJsonObjectByGzip(InputStream inputStream) {
		try {
			GZIPInputStream gzin = new GZIPInputStream(inputStream);
			StringBuilder builder = new StringBuilder();
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(gzin));
			String line = "";
			while ((line = bufferedReader.readLine()) != null) {
				builder.append(line);
			}
			JSONObject jsonObject = new JSONObject(builder.toString());
			return jsonObject;
		} catch (Exception e) {
			log.error("", e);
			return null;
		}
	}

	public boolean isStartWithHttp(String url) {
		if (url.startsWith("http")) {
			return true;
		}
		return false;
	}
}
